<!-- 文章详情页 -->
<template>
  <div class="article">
    <!-- 导航栏 -->
    <van-nav-bar style="background-color: #F3F3F3;" fixed>
      <template #title>
        <span style="font-size: 18px; color: #FF8800">老中网新闻</span>
      </template>
      <template #left>
        <van-icon @click="onBack" name="arrow-left" size="20px" color="gray" style="font-weight: bold;width: 20px"/>
      </template>
      <van-icon name="star-o" size="20px" color="gray" style="font-weight: bold"/>
      <template #right>
        <van-icon @click="onFavorite" :name="article.isFavorite?'star':'star-o'" size="20px" :color="article.isFavorite?'#FF8800':'gray'" style="font-weight: bold"/>
        <van-icon @click="onShare" name="ellipsis" size="20px" color="gray" style="font-weight: bold; margin-left: 15px"/>
      </template>
    </van-nav-bar>
    <div v-if="article.id > 0">
      <div class="wrapper" style="width: 92%;margin:0 auto">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="margin-top: 40px">
          <!-- 标题 -->
          <h3 style="text-align: left">{{article.title}}</h3>
          <!-- 阅读 评论 -->
          <div style="text-align: left">
            <span style="font-size: 12px">{{article.readCount || 0}}阅读</span>
            <span style="font-size: 12px; margin-left: 10px">{{article.commentCount || 0}}评论</span>
          </div>
          <!-- 作者 关注 -->
          <div style="margin-top: 20px">
            <van-row>
              <van-col span="12">
                <Author :name="article.author.nick || '作者昵称'" :time="this.$util.getDateDiff(article.time)" :img="article.author.avatar"></Author>
              </van-col>
              <van-col class="sign-right" span="12">
                <van-button @click="onFollow" size="small" :color="article.isFollow? 'gray' : '#FF8800'" style="font-size: 14px">{{article.isFollow?'已关注':'关注'}}</van-button>
              </van-col>
            </van-row>
          </div>
          <!-- 内容 -->
          <div class="article-content">
            <div style="text-align: left;font-size: 16px" @click="onPreviewIMG" v-html="article.content || '文章内容'"></div>
          </div>

          <!-- 声明 -->
          <p class="statement">{{statement}}</p>
          <!-- 打赏 -->
          <p>【感谢您的赏脸阅读】</p>
          <van-button ref="divComment" @click="onReward" color="Crimson" size="small" style="font-size: 14px; width: 70px; height: 35px" >打赏</van-button>
        </van-pull-refresh>
      </div>
      <!-- 评论 -->
      <van-divider :style="divStyle">评论</van-divider>
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" offset="10">
        <van-cell v-for="(item, idx) in comments" :key="idx">
          <div>
            <!-- 评论者-楼层 -->
            <div class="comment-user">
              <Author :name="item.author.nick" :img="item.author.avatar"></Author>
              <div class="comment-font">{{ $util.getFloor(item.lineNum) }}</div>
            </div>
            <!-- 引用回复内容 -->
            <div v-if="item.refContent" class="comment-font comment-old">
              <div>{{item.refAuthor.nick + ' 发表于 ' + $util.getDate(item.refTime) }}</div>
              <div v-html="item.refContent"></div>
            </div>
            <!-- 评论内容 -->
            <div class="comment-content" @click="onPreviewIMGComment" v-html="item.content"></div>
            <div class="comment-bar">
              <div class="comment-time">{{$util.getDate(item.time)}}</div>
              <div class="comment-bar-icon comment-font">
                <van-icon @click="onPraiseComment(item)" :color="item.isPraised?'#FF8800':'gray'" :name="item.isPraised?'good-job':'good-job-o'" size="20"/>
                <span style="margin-right: 30px">{{item.praiseCount}}</span>
                <van-icon @click="onReplyComment(item.id)" name="chat-o" size="20" />
              </div>
            </div>
          </div>
        </van-cell>
      </van-list>
      <!-- 底部bar -->
      <ArticleFootBar
        :onComment="onComment"
        :onGood="onPraiseArticle"
        :onShare="onShare"
        :onGoToComment="gotoComment"
        :iconGood = "article.isPraised?'good-job':'good-job-o'"
        :goodColor = "article.isPraised?'#FF8800':'gray'"
        :commentCnt = "article.commentCount"
        :praiseCnt = "article.praiseCount"
      >
      </ArticleFootBar>
      <!-- 分享 -->
      <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options"
        @select="onShareChose"
      />
    </div>
    <!-- 图片预览 -->
    <van-image-preview
      v-model="imgShow"
      :images="imgSrc"
      :show-index="imgSrc.length>1"
      :start-position="imgIndex"
    >
    </van-image-preview>
  </div>
</template>

<script>
import Author from '@/components/Author.vue'
import ArticleFootBar from '@/components/ArticleFootBar.vue'
export default {
  name: 'ArticleDetail',
  components: {
    Author,
    ArticleFootBar
  },
  props: ['id'],
  data () {
    return {
      article: {}, // 文章详细
      comments: [], // 评论
      loading: false, // 评论加载标识
      finished: false, // 评论加载完成标识
      refreshing: false, // 刷新标识
      divStyle: { color: 'DarkGray', borderColor: 'DarkGray', padding: '0px 16px' },
      statement: '帖子观点仅代表作者本人，不代表官方立场，老中网App为信息发布平台，对帖子内容及观点保持中立态度，如帖子内容涉及到您的权益，请联系老中网官方进行删帖。',
      // 分享
      showShare: false,
      options: [
        [
          { name: '微信', icon: 'wechat' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' }
        ],
        [
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' }
        ]
      ],
      // 图片预览
      imgShow: false,
      imgSrc: [],
      imgIndex: 0,
      // 评论相关
      commentSort: 0, // 0时间ASC 1时间DESC
      currCommentNum: 0, // 评论分页-起始
      numCommentPerPage: 10 // 评论分页-每页数量
    }
  },
  // 页面激活
  activated () {
    console.log('-----activated', this.article.id, this.$route.query.id)
    if (this.article.id !== parseInt(this.$route.query.id)) {
      this.article = {}
      this.article.id = 0
      this.comments = []
      this.commentSort = 0
      this.currCommentNum = 0
      this.numCommentPerPage = 3
      this.finished = false
      this.onLoad()
    }
  },
  methods: {
    onLoad () {
      if (this.refreshing) {
        this.article = {}
        this.comments = []
        this.refreshing = false
        this.commentSort = 0
        this.currCommentNum = 0
        this.numCommentPerPage = 3
      }
      console.log('=======' + this.$route.query.id)
      // 加载文章信息
      Promise.all(
        [this.$api.getArticleReq({ id: parseInt(this.$route.query.id), userId: 2 }),
          this.$api.getCommentListReq(
            {
              id: parseInt(this.$route.query.id),
              beginNum: this.currCommentNum,
              count: this.numCommentPerPage,
              orderBy: 0
            })
        ]
      )
        .then(
          (resp) => {
            this.article = resp[0].article
            this.comments = this.comments.concat(resp[1].commentList)
            this.currCommentNum = this.currCommentNum + resp[1].commentList.length
            if (this.currCommentNum >= this.article.commentCount) {
              this.finished = true
            }
            // 记录浏览历史
            let timeNow = this.$util.timeNow()
            console.log('timeNow', timeNow)
            this.$localStore.addReadHistory(this.article.id, this.article.title, timeNow)
          }
        )
        .catch(
          (err) => {
            console.log('获取信息失败' + err)
          }
        )
      this.loading = false
    },
    // 刷新
    onRefresh () {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    // 返回
    onBack () {
      this.article = {}
      this.$router.back()
    },
    // 收藏
    onFavorite () {
      this.$api.favoriteReq({ id: this.article.id, flag: this.article.isFavorite === 1 ? 0 : 1 })
        .then(
          (resp) => {
            if (resp.errMsg === 'OK') {
              console.log('=========!!!!!', resp)
              this.article.isFavorite = (this.article.isFavorite === 1 ? 0 : 1)
              if (this.article.isFavorite) {
                this.$toast({ message: '收藏成功', duration: 1000 })
              } else {
                this.$toast({ message: '取消收藏', duration: 1000 })
              }
            }
          })
    },
    // 关注
    onFollow () {
      let reqData = { id: this.article.author.id, flag: this.article.isFollow === 1 ? 0 : 1 }
      this.$api.followReq(reqData)
        .then((resp) => {
          if (resp.errMsg === 'OK') {
            this.article.isFollow = (this.article.isFollow === 1 ? 0 : 1)
            if (this.article.isFollow) {
              this.$toast({ message: '关注成功', duration: 1000 })
            } else {
              this.$toast({ message: '取消关注', duration: 1000 })
            }
          }
        })
    },
    // 分享
    onShare () {
      this.showShare = true
    },
    // 选择分享方式
    onShareChose (option) {
      this.showShare = false
    },
    // 打赏
    onReward () {
      // 是否登录
      if (!this.$store.getters.GetUserToken) {
        this.$router.push('/login')
        return
      }
      this.$router.push('/reward')
    },
    // 点赞评论
    onPraiseComment (item) {
      let req = { id: item.id, type: 1, flag: item.isPraised === 1 ? 0 : 1 }
      this.$api.praiseReq(req)
        .then((resp) => {
          if (resp.errMsg === 'OK') {
            item.isPraised = req.flag
            if (req.flag === 1) {
              item.praiseCount = item.praiseCount + 1
              this.$toast('点赞' + item.lineNum + '楼')
            } else {
              item.praiseCount = item.praiseCount - 1
            }
          }
        })
    },
    // 点赞文章
    onPraiseArticle () {
      let req = { id: this.article.id, type: 0, flag: this.article.isPraised === 1 ? 0 : 1 }
      this.$api.praiseReq(req)
        .then((resp) => {
          if (resp.errMsg === 'OK') {
            this.article.isPraised = req.flag
            if (req.flag === 1) {
              this.article.praiseCount = this.article.praiseCount + 1
              this.$toast('点赞文章')
            } else {
              this.article.praiseCount = this.article.praiseCount - 1
            }
          }
        })
    },
    // 评论文章
    onComment () {
      this.$router.push({ path: '/edit', query: { flag: 0, type: 0, id: this.$route.query.id } })
    },
    // 回复评论
    onReplyComment (id) {
      this.$router.push({ path: '/edit', query: { flag: 1, type: 0, id: id } })
    },
    // 跳转评论
    gotoComment () {
      this.$refs.divComment.scrollIntoView()
    },
    // 预览图片
    onPreviewIMG (e) {
      console.log('内容点击======', e)
      if (e.target.tagName === 'IMG') {
        this.imgSrc = []
        let idx = 0
        // 计算图片index
        for (let i = 0; i < this.article.images.length; i++) {
          this.imgSrc.push(this.article.images[i])
          // 看上去相等，但就是不等，用trim后可以了
          if (this.article.images[i].trim() === e.target.currentSrc.trim()) {
            idx = i
            console.log('00000000000000', i, idx)
          }
        }
        this.imgShow = true
        this.imgIndex = idx
        // ImagePreview({ images: this.article.images, startPosition: idx, swipeDuration: 300 })
      }
    },
    // 预览评论图片
    onPreviewIMGComment (e) {
      if (e.target.tagName === 'IMG') {
        this.imgSrc = []
        this.imgSrc[0] = e.target.currentSrc
        this.imgIndex = 0
        // ImagePreview({ images: [img], showIndex: false, swipeDuration: 300 })
        this.imgShow = true
      }
    }
  },
  computed: {
    // article () {
    //   let atc = localStorage.getItem('Article')
    //   return JSON.parse(atc)
    // }
  }
}
</script>

<style scoped>
  .sign-left{
    text-align: left;
  }
  .sign-right{
    text-align: right;
  }
  .statement{
    color: gray;
    font-size: 12px;
  }
  .van-cell{
    padding: 10px 20px;
  }
  .comment-user{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .comment-content{
    margin: 10px 10px;
    font-size: 16px;
  }
  .comment-bar{
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding-left: 10px;
    color: #A0A0A0;
    font-size: 16px;
  }
  .comment-bar-icon{
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }
  .comment-font{
    color: #A0A0A0;
    font-size: 16px;
  }
  .comment-time{
    font-size: 14px;
  }
  .comment-old{
    margin: 10px 10px;
    background-color: #F0F0F0;
    padding: 5px 10px;
    border-radius: 3px;
  }
  /* 评论的图片样式(v-html) */
  .comment-content >>> .content-img{
    height: 100px;
    width: 33%;
    object-fit: cover;
  }
  /* 被引用的评论的图片样式(v-html) */
  .comment-old >>> .content-img{
    height: 100px;
    width: 33%;
    object-fit: cover;
  }
  .article-content >>> .content-img{
    width: 100%;
  }
</style>
